package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.entity.Store;
import com.foodorder.service.StoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 店铺控制器
 */
@RestController
@RequestMapping("/stores")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class StoreController {
    
    private final StoreService storeService;
    
    /**
     * 获取附近店铺列表
     */
    @GetMapping("/nearby")
    public ApiResponse<List<Store>> getNearbyStores(
            @RequestParam Double latitude,
            @RequestParam Double longitude,
            @RequestParam(defaultValue = "10.0") Double radius) {
        
        List<Store> stores = storeService.findNearbyStores(latitude, longitude, radius);
        return ApiResponse.success(stores);
    }
    
    /**
     * 按销量获取店铺列表
     */
    @GetMapping("/by-sales")
    public ApiResponse<Page<Store>> getStoresBySales(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Store> stores = storeService.findStoresByMonthlySales(pageable);
        return ApiResponse.success(stores);
    }
    
    /**
     * 按评分获取店铺列表
     */
    @GetMapping("/by-rating")
    public ApiResponse<Page<Store>> getStoresByRating(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Store> stores = storeService.findStoresByRating(pageable);
        return ApiResponse.success(stores);
    }
    
    /**
     * 管理端分页查询店铺
     */
    @GetMapping("/admin")
    public ApiResponse<Map<String, Object>> getStoresForAdmin(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String city) {
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<Store> storePage = storeService.findStoresForAdmin(keyword, status, city, pageable);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", storePage.getContent());
            result.put("total", storePage.getTotalElements());
            result.put("page", page);
            result.put("size", size);
            result.put("totalPages", storePage.getTotalPages());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("查询店铺失败: " + e.getMessage());
        }
    }
    
    /**
     * 搜索店铺
     */
    @GetMapping("/search")
    public ApiResponse<Page<Store>> searchStores(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Store> stores = storeService.searchStores(keyword, pageable);
            return ApiResponse.success(stores);
        } catch (Exception e) {
            return ApiResponse.error("搜索店铺失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取店铺详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Store> getStoreDetail(@PathVariable Long id) {
        Store store = storeService.findById(id);
        if (store == null) {
            return ApiResponse.notFound("店铺不存在");
        }
        return ApiResponse.success(store);
    }
    
    /**
     * 创建店铺
     */
    @PostMapping
    public ApiResponse<Store> createStore(@RequestBody Store store) {
        try {
            Store savedStore = storeService.save(store);
            return ApiResponse.success(savedStore);
        } catch (Exception e) {
            return ApiResponse.error("创建店铺失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新店铺
     */
    @PutMapping("/{id}")
    public ApiResponse<Store> updateStore(@PathVariable Long id, @RequestBody Store store) {
        try {
            Store existingStore = storeService.findById(id);
            if (existingStore == null) {
                return ApiResponse.error("店铺不存在");
            }
            store.setId(id);
            Store savedStore = storeService.save(store);
            return ApiResponse.success(savedStore);
        } catch (Exception e) {
            return ApiResponse.error("更新店铺失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除店铺
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteStore(@PathVariable Long id) {
        try {
            Store store = storeService.findById(id);
            if (store == null) {
                return ApiResponse.error("店铺不存在");
            }
            storeService.deleteById(id);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("删除店铺失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除店铺
     */
    @DeleteMapping("/batch")
    public ApiResponse<Void> deleteStores(@RequestBody List<Long> ids) {
        try {
            storeService.deleteByIds(ids);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("批量删除店铺失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新店铺状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateStoreStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            storeService.updateStatus(id, status);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新店铺状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算配送距离和时间
     */
    @GetMapping("/{id}/delivery-info")
    public ApiResponse<Object> getDeliveryInfo(
            @PathVariable Long id,
            @RequestParam Double latitude,
            @RequestParam Double longitude) {
        
        var deliveryInfo = storeService.calculateDeliveryInfo(id, latitude, longitude);
        return ApiResponse.success(deliveryInfo);
    }
    
    /**
     * 获取所有营业中的店铺
     */
    @GetMapping("/open")
    public ApiResponse<List<Store>> getOpenStores() {
        List<Store> stores = storeService.findOpenStores();
        return ApiResponse.success(stores);
    }
    
    /**
     * 获取店铺统计信息
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Object>> getStoreStatistics() {
        try {
            Map<String, Object> statistics = storeService.getStoreStatistics();
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            return ApiResponse.error("获取店铺统计失败: " + e.getMessage());
        }
    }
} 